from rest_framework import serializers
from django.contrib.auth.models import User
from .models import MCPServer, MCPServerFromReadme, MCPServerTag

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'email')

class MCPServerSerializer(serializers.ModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.username')
    
    class Meta:
        model = MCPServer
        fields = [
            'id', 'name', 'description', 
            'status', 'created_at', 'updated_at', 
            'owner', 'category', 'category_name', 'tags'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at']
        
    def create(self, validated_data):
        return MCPServer.objects.create(**validated_data)

class MCPServerTagSerializer(serializers.ModelSerializer):
    class Meta:
        model = MCPServerTag
        fields = ['tag']

class MCPServerFromReadmeSerializer(serializers.ModelSerializer):
    server_tags = MCPServerTagSerializer(many=True, read_only=True)
    readme_content = serializers.SerializerMethodField()
    
    class Meta:
        model = MCPServerFromReadme
        fields = ['id', 'name', 'provider', 'description', 'url', 'github', 
                 'is_official', 'category', 'category_name', 'tags', 
                 'language', 'scope', 'os', 'server_tags', 'readme_content']
    
    def get_readme_content(self, obj):
        """获取GitHub仓库的README内容"""
        if not obj.github:
            return None
            
        try:
            # 从GitHub URL中提取用户名和仓库名
            parts = obj.github.strip('/').split('/')
            if len(parts) >= 5:  # https://github.com/username/repo
                username = parts[-2]
                repo = parts[-1]
                return f"https://raw.githubusercontent.com/{username}/{repo}/main/README.md"
        except Exception:
            pass
            
        return None

    def create(self, validated_data):
        validated_data['owner'] = self.context['request'].user
        return super().create(validated_data) 